package com.twang.stock.service.jinyan;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.entity.StockFinanceReport;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.mapper.StockFinanceReportMapper;
import com.twang.stock.utils.clawer.HttpHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * http://data.10jqka.com.cn/financial/yjgg/###
 */
@Slf4j
@Service
public class StockFinanceReportService {
    private static final String USER_AGENT = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36";
    /*
        http://data.10jqka.com.cn/ajax/yjgg/date/2020-12-31/board/ALL/field/DECLAREDATE/order/desc/page/1/ajax/1/free/1/
     */
    private static final String BASE_URL_INDEX = "http://data.10jqka.com.cn/ajax/yjgg/date/";
    private static final String BASE_URL_MIDDLE = "/board/ALL/field/DECLAREDATE/order/desc/page/";
    private static final String BASE_URL_LAST = "/ajax/1/free/1/";
    private static int BASE_PAGE_NUMBER = 1;
    //public static final String URL_一季报 = "http://data.10jqka.com.cn/ajax/yjgg/date/2020-03-31/board/ALL/field/DECLAREDATE/order/desc/page/";
    public static final String URL_一季报 = "http://data.10jqka.com.cn/ajax/yjgg/date/2020-03-31/board/ALL/field/DECLAREDATE/order/desc/page/";
    public static final String URL_中报 = "http://data.10jqka.com.cn/ajax/yjgg/date/2020-06-30/board/ALL/field/DECLAREDATE/order/desc/page/";
    public static final String URL_三季报 = "http://data.10jqka.com.cn/ajax/yjgg/date/2020-09-30/board/ALL/field/DECLAREDATE/order/desc/page/";
    public static final String URL_年报 = "http://data.10jqka.com.cn/ajax/yjgg/date/2020-12-31/board/ALL/field/DECLAREDATE/order/desc/page/";

    @Resource
    private StockFinanceReportMapper stockFinanceReportMapper;

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;

    private static Integer MONEY_DW_亿=1;
    private static Integer MONEY_DW_万=2;

    private static BigDecimal setBigDe(BigDecimal money,Integer intType) {
        if (MONEY_DW_亿.intValue() == intType.intValue()) {
            return money;
        } else if (MONEY_DW_万.intValue() == intType.intValue()) {
            return money.divide(new BigDecimal(10000));
        } else {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 查询报表，以及最新业绩预告
     */
    public void excuteRepaotquery(int page,String year,String time,String quarter,int quarterNum ) {
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        StringBuffer url = new StringBuffer("").append(BASE_URL_INDEX+time+BASE_URL_MIDDLE + page + BASE_URL_LAST);
        try {
            Thread.sleep(1000);
            // 停留一秒后开始任务
            // 发送请求，并执行
            String htmlForStock = HttpHelper.getHtmlStrByUrl(url.toString(), httpClient, USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", htmlForStock);
            Document doc = Jsoup.parse(htmlForStock);
            // 获取table表的行集合元素
            // 获取table表的行集合元素
            Elements trs = doc.select("table[class=m-table J-ajax-table J-canvas-table]").select("tr");
            int pageSize = 0;
            try {
                pageSize = Integer.valueOf(doc.getElementsByClass("changePage").get(doc.getElementsByClass("changePage").size() - 1).attr("page"));
            } catch (Exception ex) {
                log.info("error ={}", ex);
            }

            for (int j = 1 + 1; j < trs.size(); j++) {
                Elements tds = trs.get(j).select("td");
                StockFinanceReport stockFinanceReport = new StockFinanceReport();
                try {
                    String stockCode = tds.get(1).select("a").html();
                    stockFinanceReport.setStockCode(stockCode);
                    //
                    stockFinanceReport.setStockAlias(tds.get(2).select("a").html());
                    //stockFinanceReport.setYear(tds.get(3).html().split("-")[0]);
                    stockFinanceReport.setYear(year);
                    stockFinanceReport.setQuarter(quarter);
                    stockFinanceReport.setQuarterNum(quarterNum);
                    stockFinanceReport.setDeclasredDate(setNoyNull(tds.get(3).html()));
                    stockFinanceReport.setZysr(new BigDecimal(setNoyNull(tds.get(4).html()).replace("亿", "").replace("万", "")));
                    stockFinanceReport.setZysrDw(setNoyNull(tds.get(4).html()).contains("亿") ? MONEY_DW_亿 : MONEY_DW_万);
                    stockFinanceReport.setZysrRise(new BigDecimal(setNoyNull(tds.get(5).html())));
                    stockFinanceReport.setZysrYysrhbzz(new BigDecimal(setNoyNull(tds.get(5).html())));
                    stockFinanceReport.setJlr(new BigDecimal(setNoyNull(tds.get(7).html()).replace("亿", "").replace("万", "")));
                    stockFinanceReport.setJlrDw(setNoyNull(tds.get(7).html()).contains("亿") ? MONEY_DW_亿 : MONEY_DW_万);
                    stockFinanceReport.setJlrRise(new BigDecimal(setNoyNull(tds.get(8).html())));
                    stockFinanceReport.setJlrYysrhbzz(new BigDecimal(setNoyNull(tds.get(9).html())));
                    stockFinanceReport.setMgsy(new BigDecimal(setNoyNull(tds.get(10).html())));
                    stockFinanceReport.setMgjzc(new BigDecimal(setNoyNull(tds.get(11).html())));
                    stockFinanceReport.setJzcsyl(new BigDecimal(setNoyNull(tds.get(12).html())));
                    stockFinanceReport.setMgjyxjl(new BigDecimal(setNoyNull(tds.get(13).html())));
                    stockFinanceReport.setXsmll(new BigDecimal(setNoyNull(tds.get(14).html())));
                    Example example = new Example(StockFinanceReport.class);
                    example.createCriteria().andEqualTo("stockCode", stockFinanceReport.getStockCode()).andEqualTo("year", stockFinanceReport.getYear())
                            .andEqualTo("quarter", stockFinanceReport.getQuarter());
                    List<StockFinanceReport> stockList = stockFinanceReportMapper.selectByExample(example);
                    if (!CollectionUtils.isEmpty(stockList)) {
                        stockFinanceReportMapper.updateByExample(stockFinanceReport, example);
                    } else {
                        stockFinanceReportMapper.insert(stockFinanceReport);
                    }
                } catch (Exception e) {
                    log.error(" 读取个股数据  data={} ,error={}", JSONObject.toJSONString(stockFinanceReport), e);
                }
            }
            if (page < pageSize) {
                page++;
                excuteRepaotquery(page, year,time,quarter, quarterNum );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static String setNoyNull(Object obj) {
        if (null == obj) {
            return "0";
        } else if (StringUtils.isEmpty(obj.toString())) {
            return "0";
        }
         obj=obj.toString();
        if(obj.toString().length()==1){
           return obj.toString().replace("-", "0");
        }
        return obj.toString();
    }
    /**
     * 根据Code生成报表
     * http://data.10jqka.com.cn/ajax/yjgg/op/code/code/000422/ajax/1/free/1/
     */
    public  void excuteRepaotqueryByCode(String code,String name) {
        String url="http://data.10jqka.com.cn/ajax/yjgg/op/code/code/"+code+"/ajax/1/free/1/";
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        try {
            Thread.sleep(1000);
            // 停留一秒后开始任务
            // 发送请求，并执行
            String htmlForStock = HttpHelper.getHtmlStrByUrl(url.toString(), httpClient, USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", htmlForStock);
            Document doc = Jsoup.parse(htmlForStock);
            // 获取table表的行集合元素
            // 获取table表的行集合元素
            Elements trs = doc.select("table[class=m-table J-ajax-table]").select("tr");
            for (int j = 1 + 1; j < 9; j++) {
                Elements tds = trs.get(j).select("td");
                StockFinanceReport stockFinanceReport = new StockFinanceReport();
                try {
                    stockFinanceReport.setStockCode(code);
                    //
                    stockFinanceReport.setStockAlias(name);
                    //stockFinanceReport.setYear(tds.get(3).html().split("-")[0]);
                    String text=tds.get(1).html();
                    stockFinanceReport.setYear(text.substring(0,4));

                    if(text.contains("一季报")){
                        stockFinanceReport.setQuarter("一季报");
                        stockFinanceReport.setQuarterNum(1);
                    }
                    if(text.contains("中报")){
                        stockFinanceReport.setQuarter("中报");
                        stockFinanceReport.setQuarterNum(2);
                    }
                    if(text.contains("三季报")){
                        stockFinanceReport.setQuarter("三季报");
                        stockFinanceReport.setQuarterNum(3);
                    }
                    if(text.contains("年报")){
                        stockFinanceReport.setQuarter("年报");
                        stockFinanceReport.setQuarterNum(4);
                    }
                    stockFinanceReport.setDeclasredDate(setNoyNull(tds.get(2).html()));
                    stockFinanceReport.setZysr(new BigDecimal(setNoyNull(tds.get(3).html()).replace("亿", "").replace("万", "")));
                    stockFinanceReport.setZysrDw(setNoyNull(tds.get(3).html()).contains("亿") ? MONEY_DW_亿 : MONEY_DW_万);
                    stockFinanceReport.setZysrRise(new BigDecimal(setNoyNull(tds.get(4).html())));
                    stockFinanceReport.setZysrYysrhbzz(new BigDecimal(setNoyNull(tds.get(5).html())));
                    stockFinanceReport.setJlr(new BigDecimal(setNoyNull(tds.get(6).html()).replace("亿", "").replace("万", "")));
                    stockFinanceReport.setJlrDw(setNoyNull(tds.get(6).html()).contains("亿") ? MONEY_DW_亿 : MONEY_DW_万);
                    stockFinanceReport.setJlrRise(new BigDecimal(setNoyNull(tds.get(7).html())));
                    stockFinanceReport.setJlrYysrhbzz(new BigDecimal(setNoyNull(tds.get(8).html())));
                    stockFinanceReport.setMgsy(new BigDecimal(setNoyNull(tds.get(9).html())));
                    stockFinanceReport.setMgjzc(new BigDecimal(setNoyNull(tds.get(10).html())));
                    stockFinanceReport.setJzcsyl(new BigDecimal(setNoyNull(tds.get(11).html())));
                    stockFinanceReport.setMgjyxjl(new BigDecimal(setNoyNull(tds.get(12).html())));
                    stockFinanceReport.setXsmll(new BigDecimal(setNoyNull(tds.get(13).html())));
                    Example example = new Example(StockFinanceReport.class);
                    example.createCriteria().andEqualTo("stockCode", stockFinanceReport.getStockCode()).andEqualTo("year", stockFinanceReport.getYear())
                            .andEqualTo("quarter", stockFinanceReport.getQuarter());
                    List<StockFinanceReport> stockList = stockFinanceReportMapper.selectByExample(example);
                    if (!CollectionUtils.isEmpty(stockList)) {
                        stockFinanceReportMapper.updateByExample(stockFinanceReport, example);
                    } else {
                        stockFinanceReportMapper.insert(stockFinanceReport);
                    }
                } catch (Exception e) {
                    log.error(" 读取个股数据  data={} ,error={}", JSONObject.toJSONString(stockFinanceReport), e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据Code删除
     * @param code
     * @return
     */
    public int  deletedByCode(String code){
        if(!StringUtils.isEmpty(code)){
            StockFinanceReport param=new StockFinanceReport();
            param.setStockCode(code);
           return  stockFinanceReportMapper.delete(param);
        }
        return 0;
    }

    /**
     * 根据Code删除
     * @param code
     * @return
     */
    public List<StockFinanceReport>  queryByCodeDesc(String code){
        if(!StringUtils.isEmpty(code)){
            Example example = new Example(StockFinanceReport.class);
            example.createCriteria().andEqualTo("stockCode", code).andNotEqualTo("year","2019");
            example.orderBy("id").asc();
            List<StockFinanceReport> stockList = stockFinanceReportMapper.selectByExample(example);
            return  stockList;
        }
        return null;
    }

}
